package org.cboard.services;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.cboard.dao.DatasetDao;
import org.cboard.dao.DatasourceDao;
import org.cboard.dao.WidgetDao;
import org.cboard.dao.WidgetLinkDao;
import org.cboard.pojo.DashboardDataset;
import org.cboard.pojo.DashboardWidget;
import org.cboard.pojo.DashboardWidgetLink;
import org.cboard.services.role.RolePermission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.cboard.security.utils.PropertiesLoader;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by yfyuan on 2016/8/22.
 */
@Repository
public class WidgetService {

    private static PropertiesLoader loader = new PropertiesLoader("ui_config.properties");

    @Autowired
    private WidgetDao widgetDao;

    @Autowired
    private DatasetDao datasetDao;

    @Autowired
    private DatasourceDao datasourceDao;
    
    public ServiceStatus save(String userId, String json) {
        JSONObject jsonObject = JSONObject.parseObject(json);
        DashboardWidget widget = new DashboardWidget();
        widget.setUserId(userId);
        widget.setName(jsonObject.getString("name"));
        widget.setData(jsonObject.getString("data"));
        widget.setCategoryName(jsonObject.getString("categoryName"));
        if (StringUtils.isEmpty(widget.getCategoryName())) {
            widget.setCategoryName("默认分类");
        }
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("widget_name", widget.getName());
        paramMap.put("user_id", widget.getUserId());
        paramMap.put("category_name", widget.getCategoryName());

        if (widgetDao.countExistWidgetName(paramMap) <= 0) {
            widgetDao.save(widget);
            return new ServiceStatus(ServiceStatus.Status.Success, "保存成功");
        } else {
            return new ServiceStatus(ServiceStatus.Status.Fail, "名称已存在");
        }
    }

    public ServiceStatus update(String userId, String json) {
        JSONObject jsonObject = JSONObject.parseObject(json);
        DashboardWidget widget = new DashboardWidget();
        widget.setUserId(userId);
        widget.setId(jsonObject.getLong("id"));
        widget.setName(jsonObject.getString("name"));
        widget.setCategoryName(jsonObject.getString("categoryName"));
        widget.setData(jsonObject.getString("data"));
        if (StringUtils.isEmpty(widget.getCategoryName())) {
            widget.setCategoryName("默认分类");
        }
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("widget_name", widget.getName());
        paramMap.put("user_id", widget.getUserId());
        paramMap.put("widget_id", widget.getId());
        paramMap.put("category_name", widget.getCategoryName());
        if (widgetDao.countExistWidgetName(paramMap) <= 0) {
            widgetDao.update(widget);
            return new ServiceStatus(ServiceStatus.Status.Success, "修改成功");
        } else {
            return new ServiceStatus(ServiceStatus.Status.Fail, "名称已存在");
        }
    }

    public ServiceStatus delete(String userId, Long id) {
        widgetDao.delete(id, userId);
        return new ServiceStatus(ServiceStatus.Status.Success, "删除成功");
    }

    public ServiceStatus checkRule(String userId, Long widgetId) {
        //自定义Ui的类型
        String userDefinedUiTypeStr = loader.getProperty("user_defined_ui_type");
        List<String> userDefinedUiTypeList = Arrays.asList(userDefinedUiTypeStr.split(","));
        DashboardWidget widget = widgetDao.getWidget(widgetId);
        if (widget == null) {
            return null;
        }
        JSONObject object = (JSONObject) JSONObject.parse(widget.getData());
        //放开对自定义UI 的dataSet和dataSource的判断拦截
        JSONObject chartTypeJsonObj = (JSONObject) object.get("config");
        if (chartTypeJsonObj != null) {
            Object chartType = chartTypeJsonObj.get("chart_type");
            if (chartType != null && userDefinedUiTypeList.contains(chartType.toString())) {
                return new ServiceStatus(ServiceStatus.Status.Success, "成功");
            }
        }

        Long datasetId = object.getLong("datasetId");
        if (datasetId != null) {
            if (datasetDao.checkDatasetRole(userId, datasetId, RolePermission.PATTERN_READ) == 1) {
                return new ServiceStatus(ServiceStatus.Status.Success, "成功");
            } else {
                DashboardDataset ds = datasetDao.getDataset(datasetId);
                return new ServiceStatus(ServiceStatus.Status.Fail, ds.getCategoryName() + "/" + ds.getName());
            }
        } else {
            Long datasourceId = object.getLong("datasource");
            if (datasourceDao.checkDatasourceRole(userId, datasourceId, RolePermission.PATTERN_READ) == 1) {
                return new ServiceStatus(ServiceStatus.Status.Success, "成功");
            } else {
                return new ServiceStatus(ServiceStatus.Status.Fail, datasourceDao.getDatasource(datasourceId).getName());
            }
        }
    }

    public ServiceStatus checkDataSetIsStillDependent(String userId, Long dataSetId) {
        List<DashboardWidget> dashboardWidgets = widgetDao.getWidgetList(userId);
        for (DashboardWidget dashboardWidget : dashboardWidgets) {
            String dataJson = dashboardWidget.getData();
            if (!StringUtils.isEmpty(dataJson)) {
                //获取对应的数据源id
                JSONObject dataSourceConfig = JSON.parseObject(dataJson);
                if (dataSourceConfig.get("datasetId") != null) {
                    String dataSetIdJSON = dataSourceConfig.get("datasetId").toString();
                    if (dataSetIdJSON.toString().equals(dataSetId.toString())) {
                        return new ServiceStatus(ServiceStatus.Status.Fail, "删除失败，请检查对应的数据集依赖配置");
                    }
                }
            }
        }
        return new ServiceStatus(ServiceStatus.Status.Success, "");
    }

    public ServiceStatus uploadUserDefinedPicture() {
        return new ServiceStatus(ServiceStatus.Status.Active, "上传图片成功");
    }
}
